﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using FCModel;
using System.Reflection;
using FCBLL;
using MiscLib;
using System.Data;
using System.Text;
using System.Drawing;

namespace FileConverter.LAB
{
    public partial class CSVQMDResonance : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //If first time page is submitted and we have file in FileUpload control but not in session
            // Store the values to SEssion Object
            if (Session["FileUpload1"] == null && FileUpload_HookUPQPM.HasFile)
            {
                Session["FileUpload1"] = FileUpload_HookUPQPM;
                Label_QDM.Text = FileUpload_HookUPQPM.FileName;
            }
            // Next time submit and Session has values but FileUpload is Blank
            // Return the values from session to FileUpload
            else if (Session["FileUpload1"] != null && (!FileUpload_HookUPQPM.HasFile))
            {
                FileUpload_HookUPQPM = (FileUpload)Session["FileUpload1"];
                Label_QDM.Text = FileUpload_HookUPQPM.FileName;
            }
            // Now there could be another sictution when Session has File but user want to change the file
            // In this case we have to change the file in session object
            else if (FileUpload_HookUPQPM.HasFile)
            {
                Session["FileUpload1"] = FileUpload_HookUPQPM;
                Label_QDM.Text = FileUpload_HookUPQPM.FileName;
            }

            if(!this.Page.IsPostBack)
            {
                Session["dt_0"] = HookUPQPMBLL.IntiData(RB_QPM.Checked);
                Session["IntiData"] = HookUPQPMBLL.GetTransposeDT((DataTable)Session["dt_0"], true);
                Bind();
            }
        }

        protected void ImportCSVQPM_Click(object sender, EventArgs e)
        {
            if (FileUpload_HookUPQPM.PostedFile.FileName == "" || FileUpload_HookUPQPM.PostedFile.InputStream.Length < 1)
            {
                return;
            }
            try
            {
                ImportCSVQPM.Enabled = false;
                string QPMHookUPFile = Guid.NewGuid().ToString() + Path.GetExtension(FileUpload_HookUPQPM.FileName);
                if (!QPMHookUPFile.EndsWith(".CSV", StringComparison.OrdinalIgnoreCase))
                {
                    //tipsInfo.Text = "QPMHookUP 文件格式不正确";
                    return;
                }
                if (!Directory.Exists(Server.MapPath("~/CSVResonance")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/CSVResonance/"));
                }
                FileUpload_HookUPQPM.PostedFile.SaveAs(Server.MapPath("~/CSVResonance/") + QPMHookUPFile);
                DataTable dt_Excel = CommonBLL.ReadQDMFile(Server.MapPath("~/CSVResonance/") + QPMHookUPFile);
                Session["QDM"] = dt_Excel;
                GridView2.DataSource = dt_Excel;
                GridView2.DataBind();
            }
            catch (Exception ex)
            {

            }
        }

        protected void CreatefileQPM_Click(object sender, EventArgs e)
        {
            if (Label_QDM.Text == "")
            {
                //tipsInfo.Text = "没有指定文件.";
            }
            try
            {
                string col_import = string.Empty;
                DateTime dt_import = DateTime.MinValue;
                string csvFile = Server.MapPath("~/CSVResonance/") + Label_QDM.Text;
                DataTable dt_Excel = (DataTable)Session["QDM"];
                Session.Remove("QDM");


                if (CreatefileQPM.Text == "更改文件名")
                {
                    if (dt_Excel == null)
                        throw new Exception("请先打开文件！");
                    Rename.Attributes.CssStyle.Add("display", "block");
                    CreatefileQPM.Text = "确认更改并保存文件";
                }
                else if (CreatefileQPM.Text == "确认更改并保存文件")
                {
                    Rename.Attributes.CssStyle.Add("display", "none");
                    CreatefileQPM.Text = "更改文件名";

                    string filename = TextBox1.Text + "_" + TextBox2.Text + "_" + TextBox3.Text + "_" + TextBox4.Text;
                    if (RB_QPM.Checked)
                    {
                        //InsertData();
                        string sql = string.Format("select * from rt_QPM_Hookup_New(nolock) where RECORD_DATETIME='{0}'", dt_import.ToString("yyyy-MM-dd HH:mm:ss"));
                        DataTable dt_val = HookUPQPMBLL.GetData(sql);
                        string str = "";
                        string static_info = "SOF" + Environment.NewLine + "# 54-528-5111" + Environment.NewLine + "# HOOKUP" + Environment.NewLine;

                        //HookUPQPMBLL.HookUPQDMToStr(filename, static_info, TextBox4.Text.Trim(), dt_val, (DataTable)Session["InitData"], HttpContext.Current.Response, Server);
                    }
                    else
                    {
                        string sql = string.Format("select * from rt_QPMSpec_Hookup(nolock) where INIT_USE_DATETIME='{0}'", dt_import.ToString("yyyy-MM-dd HH:mm:ss"));
                        DataTable dt_val = HookUPQPMBLL.GetData(sql);
                        string str = "";
                        string static_info = "SOF" + Environment.NewLine + "# 54-528-5111" + Environment.NewLine + "# SPECS" + Environment.NewLine;
                        //InsertSpecData();
                        //SaveSpecFile(filename);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        protected void RB_QPM_CheckedChanged(object sender, EventArgs e)
        {
            Bind();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            GridView1.EditRowStyle.BackColor = Color.FromArgb(235, 235, 235);
            Bind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            Bind();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            Bind();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            //string value = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString());
            //Type tp = GetColDataType(value);
            object obj_par = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.Trim());
            object obj_val = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.Trim());
            try
            {
                #region 数据类型判断
                /*
                if (obj_val.ToString().Trim().Equals(string.Empty))
                {
                    if (!IsNull(obj_par.ToString().Trim()))
                    {
                        //MessageBox.Show("该字段不允许为空！");
                    }
                }
                else
                {
                    if (tp == Type.GetType("System.DateTime"))
                    {
                        DateTime dtime;
                        if (!DateTime.TryParse(obj_val.ToString(), out dtime))
                        {
                            //MessageBox.Show("时间格式输入不正确！");
                        }
                        else
                        {
                            DataTable dt = (DataTable)Session["IntiData"];
                            dt.Rows[e.RowIndex][1] = dtime.ToString("yyyyMMddHHmmss");
                            Session["IntiData"] = dt;
                        }
                    }
                    else if (tp == Type.GetType("System.Single"))
                    {
                        Single si;
                        if (!Single.TryParse(obj_val.ToString(), out si))
                        {
                            //MessageBox.Show("数字格式输入不正确！");
                        }
                        else
                        {
                            DataTable dt = (DataTable)Session["IntiData"];
                            dt.Rows[e.RowIndex][1] = si.ToString();
                            Session["IntiData"] = dt;   //小数的format
                        }
                    }
                    else if (tp == Type.GetType("System.Int32"))
                    {
                        Int32 i3;
                        if (!Int32.TryParse(obj_val.ToString(), out i3))
                        {
                            //MessageBox.Show("整数格式输入不正确！");
                        }
                        else
                        {
                            DataTable dt = (DataTable)Session["IntiData"];
                            dt.Rows[e.RowIndex][1] = i3.ToString();
                            Session["IntiData"] = dt;   //小数的format
                        }
                    }
                    else
                    {
                        DataTable dt = (DataTable)Session["IntiData"];
                        dt.Rows[e.RowIndex][1] = obj_val.ToString().Trim();
                    }
                }
                 */
                #endregion

                if (obj_val.ToString().Trim().Equals(string.Empty))
                {
                    if (!HookUPQPMBLL.IsNull(obj_par.ToString().Trim(), (DataTable)Session["dt_0"]))
                    {
                        //MessageBox.Show("该字段不允许为空！");
                    }
                }
                else
                {
                    DataTable dt = (DataTable)Session["IntiData"];
                    dt.Rows[e.RowIndex][1] = obj_val.ToString().Trim();
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                GridView1.EditIndex = -1;
                Bind();
            }
        }

        private void Bind()
        {
            GridView1.DataSource = (DataTable)Session["IntiData"];
            GridView1.DataBind();
        }

        private Type GetColDataType(string ColName)
        {
            return  ((DataTable)Session["dt_0"]).Columns[ColName].DataType;
        }

        protected void TextBox_Enter(object sender, EventArgs e)
        {
            if(((TextBox)sender).ID.Equals("TextBox1"))
            {
                if (TextBox1.Text == "[ToDUNS]")
                {
                    TextBox1.Focus();
                }
            }
            else if(((TextBox)sender).ID.Equals("TextBox2"))
            {
                if (TextBox2.Text == "[FromDUNS]")
                {
                    TextBox2.Focus();
                }
            }
            else if(((TextBox)sender).ID.Equals("TextBox3"))
            {
                if (TextBox3.Text == "[DocType]")
                {
                    TextBox3.Focus();
                }
            }
            else
            {
                Session["dt_import"] = DateTime.Now;
                DateTime dtime = (DateTime)Session["dt_import"];
                TextBox4.Text = dtime.ToString("yyyyMMddHHmmssfff");
            }
        }
    }
}